package com.feiyi.app.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feiyi.app.R;
import com.feiyi.app.app.AppConstant;
import com.feiyi.app.base.BaseActivity;
import com.feiyi.app.bean.RegisterBean;
import com.feiyi.app.event.LoginEvent;
import com.feiyi.app.fragment.MineFragment;
import com.feiyi.app.fragment.goodsdetail.GoodsInfoFragment;
import com.feiyi.app.net.HttpMethods;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * 作者 : wlt
 * 创建时间:  2018-07-19
 * QQ : 1346947404
 * 邮箱:wanglt_android@163.com
 * 类说明:用户登录界面
 * In me the tiger sniffs the rose
 */

public class LoginActivity extends BaseActivity {

    Unbinder unbinder;


    @BindView(R.id.et_username)
    EditText et_username;
    @BindView(R.id.et_psd)
    EditText et_psd;

    private String userName;

    private String password;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        unbinder = ButterKnife.bind(this);

    }

    /**
     * 获取当前用户输入的文字
     */
    private void getEditString(){
        userName = et_username.getText().toString();

        password = et_psd.getText().toString();

    }


    /**
     * 登录成功,记录在SP中
     * @param bean 用户登录返回的数据
     */
    private void putKeys(RegisterBean bean){
        spUtils.put(AppConstant.SID,bean.getData().getSession().getSid());//固定保存
        spUtils.put(AppConstant.UID,bean.getData().getSession().getUid());//固定保存
        spUtils.put(AppConstant.COLLECTION_NUM,bean.getData().getUser().getCollection_num());//收藏的商品数量
        spUtils.put(AppConstant.EMAIL,bean.getData().getUser().getEmail());//用户邮箱
        spUtils.put(AppConstant.ID,bean.getData().getUser().getId());//用户id,靠这个id去进行各种操作
        spUtils.put(AppConstant.NAME,bean.getData().getUser().getName());//用户名,显示的用户名
        spUtils.put(AppConstant.AWAIT_PAY,bean.getData().getUser().getOrder_num().getAwait_pay());//待付款数量
        spUtils.put(AppConstant.AWAIT_SHIP,bean.getData().getUser().getOrder_num().getAwait_ship());//待发货数量
        spUtils.put(AppConstant.FINISHED,bean.getData().getUser().getOrder_num().getFinished());//已完成订单数量
        spUtils.put(AppConstant.SHIPPED,bean.getData().getUser().getOrder_num().getShipped());//已收货数量
        spUtils.put(AppConstant.RANK_LEVEL,bean.getData().getUser().getRank_level());//积分
        spUtils.put(AppConstant.RANK_NAME,bean.getData().getUser().getRank_name());//用户等级名称
        spUtils.put(AppConstant.AVATAR,bean.getData().getUser().getAvatar());//用户头像
        spUtils.put(AppConstant.SEX,bean.getData().getUser().getSex());//用户性别
        spUtils.put(AppConstant.BIRTHDAY,bean.getData().getUser().getBirthday());//用户生日
    }

    private void doLogin(){
        getEditString();
        if (null == userName || userName.isEmpty()){
            ToastUtils.showShort("用户名不能为空");
            return;
        }
        if (null == password || password.isEmpty()){
            ToastUtils.showShort("密码不能为空");
            return;
        }
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("name",userName);
        builder.add("password",password);
        RequestBody body = builder.build();
        HttpMethods.getInstance().info.doLogin(AppConstant.LOGIN_URL,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RegisterBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(RegisterBean registerBean) {
                        if (registerBean.getStatus().getSucceed() == 1){//登录成功
                            Log.e("main", "onNext: "+registerBean );
                            ToastUtils.showShort("登录成功");
                            putKeys(registerBean);
                            if (MineFragment.isAttatched){
                                EventBus.getDefault().post(new LoginEvent(registerBean));
                            }
                            if (GoodsInfoFragment.isAttatched){
                                EventBus.getDefault().post(new LoginEvent(registerBean));
                            }
                            finish();
                        }else {//登录失败
                            ToastUtils.showShort(registerBean.getStatus().getError_desc());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @OnClick({R.id.iv_back_titlebar,R.id.but_login,R.id.tv_login_regist,R.id.tv_forget_psd})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_back_titlebar:
                finish();
                break;
            case R.id.but_login:
                doLogin();
                break;
            case R.id.tv_login_regist:
                ActivityUtils.startActivity(RegisterActivity.class);
                break;
            case R.id.tv_forget_psd:
                ActivityUtils.startActivity(ForgetPasswordActivity.class);
                break;
        }
    }
}
